<template>
  <div class="home">
    <!-- 头部导航 -->
    <header class="header">
      <div class="container">
        <div class="header-content">
          <div class="logo">
            <div class="logo-icon">
              <el-icon size="32"><Document /></el-icon>
            </div>
            <div class="logo-text">
              <h1>新闻资讯</h1>
              <span class="tagline">专业 · 及时 · 权威</span>
            </div>
          </div>
          
          <nav class="nav">
            <el-menu mode="horizontal" :default-active="activeCategory" @select="handleCategorySelect" class="nav-menu">
              <el-menu-item index="all" class="nav-item">
                <el-icon><Grid /></el-icon>
                <span>全部</span>
              </el-menu-item>
              <el-menu-item 
                v-for="category in categories" 
                :key="category.id" 
                :index="category.id.toString()"
                class="nav-item"
              >
                <el-icon v-if="getCategoryIcon(category.code)">
                  <component :is="getCategoryIcon(category.code)" />
                </el-icon>
                <span>{{ category.name }}</span>
              </el-menu-item>
            </el-menu>
          </nav>
          
          <div class="search">
            <el-input
              v-model="searchKeyword"
              placeholder="搜索新闻资讯..."
              class="search-input"
              size="large"
              @keyup.enter="handleSearch"
            >
              <template #prefix>
                <el-icon><Search /></el-icon>
              </template>
              <template #append>
                <el-button type="primary" @click="handleSearch">搜索</el-button>
              </template>
            </el-input>
          </div>
        </div>
      </div>
    </header>

    <!-- 主要内容 -->
    <main class="main">
      <div class="container">
        <div class="content">
          <!-- 左侧新闻列表 -->
          <div class="news-list">
            <div class="section-title">
              <h2>{{ currentCategoryName }}</h2>
            </div>
            
            <div v-loading="loading" class="news-grid">
              <article 
                v-for="news in newsList" 
                :key="news.id" 
                class="news-card"
                @click="goToDetail(news.id)"
              >
                <div class="news-image">
                  <img :src="news.coverImage || '/default-news.jpg'" :alt="news.title" />
                  <div v-if="news.isTop" class="top-badge">置顶</div>
                </div>
                
                <div class="news-content">
                  <h3 class="news-title">{{ news.title }}</h3>
                  <p class="news-summary">{{ news.summary }}</p>
                  
                  <div class="news-meta">
                    <span class="publish-time">{{ formatTime(news.publishTime) }}</span>
                    <div class="news-stats">
                      <span class="views">
                        <el-icon><View /></el-icon>
                        {{ news.viewCount }}
                      </span>
                      <span class="likes">
                        <el-icon><Star /></el-icon>
                        {{ news.likeCount }}
                      </span>
                    </div>
                  </div>
                </div>
              </article>
            </div>
            
            <!-- 分页 -->
            <div class="pagination">
              <el-pagination
                v-model:current-page="currentPage"
                v-model:page-size="pageSize"
                :total="total"
                :page-sizes="[10, 20, 50]"
                layout="total, sizes, prev, pager, next, jumper"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
              />
            </div>
          </div>
          
          <!-- 右侧边栏 -->
          <aside class="sidebar">
            <!-- 热门新闻 -->
            <div class="sidebar-section">
              <h3 class="sidebar-title">热门新闻</h3>
              <div class="hot-news-list">
                <div 
                  v-for="(news, index) in hotNews" 
                  :key="news.id" 
                  class="hot-news-item"
                  @click="goToDetail(news.id)"
                >
                  <span class="rank">{{ index + 1 }}</span>
                  <div class="hot-news-content">
                    <h4 class="hot-news-title">{{ news.title }}</h4>
                    <div class="hot-news-stats">
                      <span>{{ news.viewCount }} 阅读</span>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </aside>
        </div>
      </div>
    </main>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { getNewsList, getHotNews, getCategoryList } from '@/api/news'
import { View, Star, Search, Document, Grid, Monitor, Trophy, VideoPlay, Money, House, Reading, MedicalKit, MapLocation, Car, OfficeBuilding } from '@element-plus/icons-vue'

// 路由
const router = useRouter()

// 响应式数据
const loading = ref(false)
const categories = ref([])
const newsList = ref([])
const hotNews = ref([])
const searchKeyword = ref('')
const activeCategory = ref('all')

// 分页数据
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 计算属性
const currentPage = computed({
  get: () => pagination.currentPage,
  set: (val) => pagination.currentPage = val
})

const pageSize = computed({
  get: () => pagination.pageSize,
  set: (val) => pagination.pageSize = val
})

const total = computed(() => pagination.total)

const currentCategoryName = computed(() => {
  if (activeCategory.value === 'all') return '全部新闻'
  const category = categories.value.find(c => c.id.toString() === activeCategory.value)
  return category ? category.name : '全部新闻'
})

// 方法
const fetchCategories = async () => {
  try {
    categories.value = await getCategoryList()
  } catch (error) {
    console.error('获取分类失败:', error)
  }
}

const fetchNews = async () => {
  loading.value = true
  try {
    const params = {
      page: pagination.currentPage,
      size: pagination.pageSize
    }
    
    if (activeCategory.value !== 'all') {
      params.categoryId = parseInt(activeCategory.value)
    }
    
    const data = await getNewsList(params)
    newsList.value = data.results || []
    pagination.total = data.count || 0
  } catch (error) {
    console.error('获取新闻失败:', error)
  } finally {
    loading.value = false
  }
}

const fetchHotNews = async () => {
  try {
    const data = await getHotNews({ size: 10 })
    hotNews.value = data.results || []
  } catch (error) {
    console.error('获取热门新闻失败:', error)
  }
}

const handleCategorySelect = (key) => {
  activeCategory.value = key
  pagination.currentPage = 1
  fetchNews()
}

const handleSearch = () => {
  if (!searchKeyword.value.trim()) return
  router.push({
    name: 'SearchResult',
    query: { keyword: searchKeyword.value }
  })
}

const handleSizeChange = (size) => {
  pagination.pageSize = size
  pagination.currentPage = 1
  fetchNews()
}

const handleCurrentChange = (page) => {
  pagination.currentPage = page
  fetchNews()
}

const goToDetail = (id) => {
  router.push({ name: 'NewsDetail', params: { id } })
}

const getCategoryIcon = (code) => {
  const iconMap = {
    'tech': Monitor,
    'sports': Trophy,
    'entertainment': VideoPlay,
    'finance': Money,
    'society': House,
    'education': Reading,
    'health': MedicalKit,
    'travel': MapLocation,
    'auto': Car,
    'real_estate': OfficeBuilding
  }
  return iconMap[code] || Document
}

const formatTime = (time) => {
  if (!time) return ''
  const date = new Date(time)
  const now = new Date()
  const diff = now - date
  
  if (diff < 60000) return '刚刚'
  if (diff < 3600000) return `${Math.floor(diff / 60000)}分钟前`
  if (diff < 86400000) return `${Math.floor(diff / 3600000)}小时前`
  if (diff < 604800000) return `${Math.floor(diff / 86400000)}天前`
  
  return date.toLocaleDateString()
}

// 生命周期
onMounted(() => {
  fetchCategories()
  fetchNews()
  fetchHotNews()
})
</script>

<style scoped>
.home {
  min-height: 100vh;
  background-color: #f5f7fa;
}

.container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 20px;
}

/* 头部样式 */
.header {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  box-shadow: 0 4px 20px rgba(0,0,0,0.15);
  position: sticky;
  top: 0;
  z-index: 100;
}

.header-content {
  display: flex;
  align-items: center;
  justify-content: space-between;
  height: 80px;
  padding: 0 20px;
}

.logo {
  display: flex;
  align-items: center;
  gap: 12px;
  color: white;
}

.logo-icon {
  background: rgba(255,255,255,0.2);
  border-radius: 12px;
  padding: 8px;
  backdrop-filter: blur(10px);
}

.logo-text h1 {
  font-size: 28px;
  font-weight: 700;
  margin: 0;
  background: linear-gradient(45deg, #fff, #e3f2fd);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
}

.logo-text .tagline {
  font-size: 12px;
  color: rgba(255,255,255,0.8);
  font-weight: 300;
  letter-spacing: 2px;
}

.nav {
  flex: 1;
  margin: 0 40px;
}

.nav-menu {
  background: transparent !important;
  border-bottom: none !important;
}

.nav-menu .el-menu-item {
  color: rgba(255,255,255,0.9) !important;
  border-bottom: 2px solid transparent !important;
  font-weight: 500;
  transition: all 0.3s ease;
}

.nav-menu .el-menu-item:hover,
.nav-menu .el-menu-item.is-active {
  color: #fff !important;
  background: rgba(255,255,255,0.1) !important;
  border-bottom-color: #fff !important;
  border-radius: 8px 8px 0 0;
}

.nav-item {
  display: flex;
  align-items: center;
  gap: 6px;
}

.search-input {
  width: 350px;
}

.search-input .el-input__wrapper {
  border-radius: 25px;
  box-shadow: 0 4px 12px rgba(0,0,0,0.1);
  backdrop-filter: blur(10px);
  background: rgba(255,255,255,0.95);
}

.search-input .el-button {
  border-radius: 0 25px 25px 0;
}

/* 主要内容 */
.main {
  padding: 30px 0;
}

.content {
  display: grid;
  grid-template-columns: 1fr 300px;
  gap: 30px;
}

.section-title {
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 2px solid #409eff;
}

.section-title h2 {
  color: #303133;
  font-size: 24px;
  margin: 0;
}

/* 新闻网格 */
.news-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(350px, 1fr));
  gap: 20px;
  margin-bottom: 30px;
}

.news-card {
  background: white;
  border-radius: 16px;
  overflow: hidden;
  box-shadow: 0 4px 20px rgba(0,0,0,0.08);
  cursor: pointer;
  transition: all 0.4s cubic-bezier(0.4, 0, 0.2, 1);
  border: 1px solid rgba(0,0,0,0.05);
  position: relative;
}

.news-card::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  height: 4px;
  background: linear-gradient(90deg, #667eea, #764ba2);
  opacity: 0;
  transition: opacity 0.3s ease;
}

.news-card:hover {
  transform: translateY(-8px);
  box-shadow: 0 12px 40px rgba(0,0,0,0.15);
}

.news-card:hover::before {
  opacity: 1;
}

.news-image {
  position: relative;
  height: 200px;
  overflow: hidden;
}

.news-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.top-badge {
  position: absolute;
  top: 10px;
  left: 10px;
  background: #f56c6c;
  color: white;
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
}

.news-content {
  padding: 20px;
}

.news-title {
  font-size: 18px;
  color: #303133;
  margin: 0 0 10px 0;
  line-height: 1.4;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
  font-weight: 600;
}

.news-summary {
  color: #606266;
  font-size: 14px;
  line-height: 1.5;
  margin: 0 0 15px 0;
  display: -webkit-box;
  -webkit-line-clamp: 3;
  line-clamp: 3;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.news-meta {
  display: flex;
  justify-content: space-between;
  align-items: center;
  color: #909399;
  font-size: 12px;
}

.news-stats {
  display: flex;
  gap: 15px;
}

.news-stats span {
  display: flex;
  align-items: center;
  gap: 4px;
}

/* 侧边栏 */
.sidebar {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.sidebar-section {
  background: white;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
}

.sidebar-title {
  color: #303133;
  font-size: 18px;
  margin: 0 0 15px 0;
  padding-bottom: 10px;
  border-bottom: 1px solid #ebeef5;
}

.hot-news-item {
  display: flex;
  align-items: flex-start;
  gap: 10px;
  padding: 10px 0;
  border-bottom: 1px solid #f5f7fa;
  cursor: pointer;
  transition: background-color 0.3s;
}

.hot-news-item:hover {
  background-color: #f5f7fa;
}

.hot-news-item:last-child {
  border-bottom: none;
}

.rank {
  background: #409eff;
  color: white;
  width: 20px;
  height: 20px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 12px;
  font-weight: bold;
  flex-shrink: 0;
}

.hot-news-content {
  flex: 1;
}

.hot-news-title {
  color: #303133;
  font-size: 14px;
  margin: 0 0 5px 0;
  line-height: 1.4;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.hot-news-stats {
  color: #909399;
  font-size: 12px;
}

/* 分页 */
.pagination {
  display: flex;
  justify-content: center;
  margin-top: 30px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .content {
    grid-template-columns: 1fr;
  }
  
  .news-grid {
    grid-template-columns: 1fr;
  }
  
  .header-content {
    flex-direction: column;
    height: auto;
    padding: 15px 0;
    gap: 15px;
  }
  
  .nav {
    margin: 0;
  }
  
  .search-input {
    width: 100%;
  }
}
</style>
